#!/bin/bash

# 脚本说明
# 该脚本用于启动MongoDB服务
# 脚本执行后，MongoDB服务将被启动
# 脚本执行前，请确认系统中已经安装了MongoDB

# 应用名称
APP_NAME=mongodb.sh
# MongoDB 安装路径
MONGODB_HOME=/usr/local/mongoDB
# MongoDB 启动脚本
MONGODB_BIN=$MONGODB_HOME/bin/mongod
# MongoDB 配置文件
MONGODB_CONF=$MONGODB_HOME/etc/mongo.conf

# 判断是否安装MongoDB
if [ ! -f $MONGODB_BIN ]; then
    echo "MongoDB is not installed."
    exit 1
fi

# 使用说明，用来提示输入参数
usage() {
    echo "Usage: sh MongoDB.sh {start|stop|restart|status}"
    exit 1
}

# 启动MongoDB
start() {
    echo "开始启动 MongoDB..."
    $MONGODB_BIN --config $MONGODB_CONF
    # 检测MongoDB是否启动成功
    PID=$(ps aux|grep $MONGODB_NAME | grep $MONGODB_CONF |grep -v grep |awk '{print $2}')
    if [ -z "$PID" ]; then
        echo "MongoDB start failed!"
        exit 1
    fi
    echo "MongoDB started successfully!"
}

# 停止MongoDB
stop() {
    echo "Stopping MongoDB..."
    sudo systemctl stop mongod
    PID=$(ps aux|grep $MONGODB_NAME | grep $MONGODB_CONF |grep -v grep |awk '{print $2}')
    echo $PID
    if [ -n "$PID" ]; then
        sudo kill -9 $PID
    else
        echo "MongoDB is not running."
    fi
    echo "MongoDB stopped successfully!"
}

# 重启MongoDB
restart() {
    stop
    sleep 2
    start
}

# 查看MongoDB状态
status() {
    echo "Checking MongoDB status..."
    PID=$(ps aux|grep $MONGODB_NAME | grep $MONGODB_CONF |grep -v grep |awk '{print $2}')
    # 判断是否启动MongoDB
    if [ -n "$PID" ]; then
        echo "MongoDB is running, PID: $PID"
    else
        echo "MongoDB is not running."
    fi
}

# 根据输入参数，选择执行对应方法，不输入则执行使用说明 usage() 函数
case "$1" in
start)
    start
    ;;
stop)
    stop
    ;;
restart)
    restart
    ;;
status)
    status
    ;;
*)
    usage
    ;;
esac
